using System;
using System.Collections.Generic;
using System.Windows.Forms;

namespace FileEncoder
{
    public partial class MainForm : Form
    {
        private FileEncoder fileEncoder;
        private System.ComponentModel.BackgroundWorker backgroundWorker;

        public MainForm()
        {
            InitializeComponent();
            InitializeBackgroundWorker();
            SetupFileTypeList();
        }

        private void InitializeBackgroundWorker()
        {
            backgroundWorker = new System.ComponentModel.BackgroundWorker();
            backgroundWorker.WorkerReportsProgress = true;
            backgroundWorker.WorkerSupportsCancellation = true;
            backgroundWorker.DoWork += BackgroundWorker_DoWork;
            backgroundWorker.ProgressChanged += BackgroundWorker_ProgressChanged;
            backgroundWorker.RunWorkerCompleted += BackgroundWorker_RunWorkerCompleted;
        }

        private void SetupFileTypeList()
        {
            string[] fileTypes = {
                "*.txt", "*.cpp", "*.h", "*.hpp", "*.c", "*.hxx",
                "*.cxx", "*.cc", "*.hh", "*.inl", "*.cs", "*.java",
                "*.py", "*.js", "*.html", "*.htm", "*.css", "*.xml",
                "*.json", "*.ini", "*.cfg", "*.conf", "*.log", "*.md",
                "*.pro"
            };

            foreach (string type in fileTypes)
            {
                checkedListBoxFileTypes.Items.Add(type, true);
            }
        }

        private void btnSelectDir_Click(object sender, EventArgs e)
        {
            using (FolderBrowserDialog folderDialog = new FolderBrowserDialog())
            {
                folderDialog.Description = "选择文件夹";
                folderDialog.ShowNewFolderButton = false;
                
                if (folderDialog.ShowDialog() == DialogResult.OK)
                {
                    txtDirectory.Text = folderDialog.SelectedPath;
                }
            }
        }

        private void btnStart_Click(object sender, EventArgs e)
        {
            if (string.IsNullOrWhiteSpace(txtDirectory.Text))
            {
                MessageBox.Show("请先选择文件夹！", "警告", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                return;
            }

            List<string> selectedTypes = new List<string>();
            foreach (var item in checkedListBoxFileTypes.CheckedItems)
            {
                selectedTypes.Add(item.ToString());
            }

            if (selectedTypes.Count == 0)
            {
                MessageBox.Show("请至少选择一种文件类型！", "警告", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                return;
            }

            btnStart.Enabled = false;
            btnStop.Enabled = true;
            progressBar.Value = 0;
            txtLog.Clear();

            fileEncoder = new FileEncoder();
            fileEncoder.SetTargetDir(txtDirectory.Text);
            fileEncoder.SetFileTypes(selectedTypes);
            
            fileEncoder.ProgressUpdated += FileEncoder_ProgressUpdated;
            fileEncoder.LogMessage += FileEncoder_LogMessage;
            fileEncoder.ConversionFinished += FileEncoder_ConversionFinished;
            fileEncoder.ConversionError += FileEncoder_ConversionError;

            backgroundWorker.RunWorkerAsync();
        }

        private void btnStop_Click(object sender, EventArgs e)
        {
            if (fileEncoder != null)
            {
                fileEncoder.StopConversion();
                backgroundWorker.CancelAsync();
            }
            btnStop.Enabled = false;
        }

        private void BackgroundWorker_DoWork(object sender, System.ComponentModel.DoWorkEventArgs e)
        {
            fileEncoder.StartConversion();
        }

        private void BackgroundWorker_ProgressChanged(object sender, System.ComponentModel.ProgressChangedEventArgs e)
        {
            // 由FileEncoder的事件处理
        }

        private void BackgroundWorker_RunWorkerCompleted(object sender, System.ComponentModel.RunWorkerCompletedEventArgs e)
        {
            btnStart.Enabled = true;
            btnStop.Enabled = false;
        }

        private void FileEncoder_ProgressUpdated(object sender, int e)
        {
            if (progressBar.InvokeRequired)
            {
                progressBar.Invoke(new Action(() => progressBar.Value = e));
            }
            else
            {
                progressBar.Value = e;
            }
        }

        private void FileEncoder_LogMessage(object sender, string e)
        {
            if (txtLog.InvokeRequired)
            {
                txtLog.Invoke(new Action(() => 
                {
                    txtLog.AppendText(e + Environment.NewLine);
                    txtLog.ScrollToCaret();
                }));
            }
            else
            {
                txtLog.AppendText(e + Environment.NewLine);
                txtLog.ScrollToCaret();
            }
        }

        private void FileEncoder_ConversionFinished(object sender, EventArgs e)
        {
            if (this.InvokeRequired)
            {
                this.Invoke(new Action(() => 
                {
                    MessageBox.Show("编码转换已完成！", "完成", MessageBoxButtons.OK, MessageBoxIcon.Information);
                }));
            }
            else
            {
                MessageBox.Show("编码转换已完成！", "完成", MessageBoxButtons.OK, MessageBoxIcon.Information);
            }
        }

        private void FileEncoder_ConversionError(object sender, string e)
        {
            if (this.InvokeRequired)
            {
                this.Invoke(new Action(() => 
                {
                    MessageBox.Show("转换失败: " + e, "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
                }));
            }
            else
            {
                MessageBox.Show("转换失败: " + e, "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }
    }
}
